package com.dap.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangmin
 * @discription
 * @created 2020-05-08 10:14
 */
public abstract class StackTraceUtil {
    private final static Logger logger = LoggerFactory.getLogger(StackTraceUtil.class);

    /**
     * 生成简化后的堆栈信息
     * @param st 堆栈
     * @param maxLayers 打印的最大层数 (<=0代表没有限制)
     * @param classNamePrefix 类路径的前缀, 不符合该前缀的堆栈信息不打印 (为null代表不限制)
     * @param needCGLib 是否需要CGLib生成的类的堆栈
     * */
    public static String generateStackTraceStr(StackTraceElement[] st, int maxLayers, String classNamePrefix, boolean needCGLib) {
        StringBuffer sb = new StringBuffer();
        int count = 0;
        for (StackTraceElement element : st) {
            if (classNamePrefix != null) {
                if (!element.getClassName().startsWith(classNamePrefix)) {
                    continue;
                }
            }

            if (!needCGLib) {
                if ("<generated>".equals(element.getFileName())) {
                    continue;
                }
            }

            sb.append(element.toString()).append('\n');

            ++count;
            if (maxLayers > 0 && count >= maxLayers) {
                break;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        StackTraceElement[] st = Thread.currentThread().getStackTrace();
        System.out.println(generateStackTraceStr(st, 10, "com.", false));
    }
}
